import {ApiFunction} from "./ajax";
import * as Extend from './extend'
import _ from 'lodash'

export function serverInvoke(serverJsUrl: string, args: any): Promise<any> {
    return new Promise((resolve, reject) => {
        Extend.ajax.func!({
            url: Extend.serverJsUrlTransform(serverJsUrl),
            method: 'post-json',
            data: args

        }).then(res => {
            resolve(res);

        }).catch(e => {
            reject(e);
        });
    })
}

export function brokerInvoke(serverUrl: string, method: string, args: any): Promise<any> {
    return new Promise((resolve, reject) => {
        Extend.ajax.func!({
            url: serverUrl + '@' + method,
            method: 'post-json',
            data: args

        }).then(res => {
            resolve(res);

        }).catch(e => {
            reject(e);
        });
    })
}

/**
 * 新版 Yvan-Server API 代理
 */
declare type Proxy<T> = {
    [KEY in keyof T]: T[KEY] extends (...args: any) => any ?
        (...args: Parameters<T[KEY]>) => Promise<ReturnType<T[KEY]>>
        : never
}

/**
 * 新版 Yvan-Server 引入 API 的方式
 */
export function createProxy<T>(serviceType: T): Proxy<T> {
    const serviceProxy: any = serviceType;
    const result: any = {};

    _.each(serviceProxy.funcs, funName => {
        result[funName] = function () {
            return brokerInvoke(serviceProxy.invokeUrl, funName, {
                args: Array.prototype.slice.call(arguments)
            });
        };
    });

    return result;
}
